package trystero.lib.component.parser;

import java.util.Vector;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONTokener;

import trystero.lib.component.StreamIds;
import trystero.lib.component.ReaderItemReference;

public class StreamIdsParser
{
   InputStream stream;

   public StreamIdsParser(InputStream stream)
   {
      this.stream = stream;
   }

   public StreamIds parse() throws Exception
   {
      JSONTokener t = new JSONTokener(new InputStreamReader(this.stream));
      JSONObject o = new JSONObject(t);
      return this.parse(o);
   }

   public StreamIds parse(JSONObject o) throws Exception
   {
      StreamIds ids = new StreamIds();

      JSONArray items = (JSONArray)o.get("itemRefs");
      ids.items(this.parseItemVector(items));

      return ids;
   }

   public Vector parseItemVector(JSONArray a) throws Exception
   {
      Vector v = new Vector();

      for(int i = 0; i < a.length(); i++)
      {
	 ReaderItemReference ref = this.parseItemReference((JSONObject)a.get(i)); 
	 v.add(ref);
      }

      return v;
   }

   public ReaderItemReference parseItemReference(JSONObject o) throws Exception
   {
      ReaderItemReference ref = new ReaderItemReference();

      ref.id((String)o.get("id"));
      //ref.stream((String)o.get("directStreamIds")); // XXX
      ref.timestamp(Long.parseLong((String)o.get("timestampUsec")));

      return ref;
   }
}
